package com.ztjava.core.interceptor;

import java.util.Map;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.ztjava.core.Constant;
import com.ztjava.core.annotation.BackMethod;
import com.ztjava.core.annotation.FrontMethod;
import com.ztjava.core.directive.DataDirective;
import com.ztjava.core.directive.ParamDirective;

public class CoreInterceptor implements Interceptor{
	
	private static DataDirective dataDirective = new DataDirective();
	private static ParamDirective paramDirective = new ParamDirective();

	@Override
	public void intercept(Invocation inv) {
		Controller c = inv.getController();
		String requestType = c.getRequest().getHeader("X-Requested-With");
		
		if(inv.getMethod().isAnnotationPresent(BackMethod.class)){
			Integer back_user_id = c.getSessionAttr(Constant.BackUser);
			if(back_user_id==null){
				if(requestType!=null&&requestType.equals("XMLHttpRequest")){
					c.setAttr("result", "timeout");
					c.setAttr("message", "请先登录！");
					c.renderJson(new String[]{"result","message"});
				}else {
					c.redirect("/"+Constant.BackPlugin.toLowerCase()+"/login?callback="+getCallBackUrl(inv));
				}
				return;
			}
		}else {
			Integer front_user_id = c.getSessionAttr(Constant.FrontUser);
			if(inv.getMethod().isAnnotationPresent(FrontMethod.class)){
				if(front_user_id==null){
					if(requestType!=null&&requestType.equals("XMLHttpRequest")){
						c.setAttr("result", "timeout");
						c.setAttr("message", "请先登录！");
						c.renderJson(new String[]{"result","message"});
					}else {
						c.redirect("/"+Constant.FrontPlugin.toLowerCase()+"/login?callback="+getCallBackUrl(inv));
					}	
					return;
				}
			}
			c.setAttr("front_user_id", front_user_id);
		}

		c.setAttr("toData", dataDirective);
		c.setAttr("toParam", paramDirective);
		inv.invoke();
	}
	
	private String getCallBackUrl(Invocation inv){
		String url = inv.getActionKey();
		String paramStr = "";
		Map<String,String[]> params = inv.getController().getParaMap();
		for(String key:params.keySet()){
			String[] values = params.get(key);
			for(int i=0;i<values.length;i++){
				paramStr = paramStr + "%26"+key+"="+values[i];
			}
		}
		if(!paramStr.equals("")){
			url = url + "?"+paramStr.substring(3, paramStr.length());
		}
		return url;
	}
}
